<template>
  <div class="flex flex-col h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 transition-colors duration-300">
    <!-- 顶部导航栏 -->
    <header class="bg-white dark:bg-gray-800 shadow-md z-10">
      <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <div class="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
            <i class="fa fa-comments text-white text-xl"></i>
          </div>
          <h1 class="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-500 to-purple-600">豆包AI助手</h1>
        </div>
        <div class="flex items-center space-x-4">
          <button 
            @click="toggleDarkMode" 
            class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
            aria-label="切换主题模式"
          >
            <i class="fa fa-moon-o dark:hidden text-gray-600"></i>
            <i class="fa fa-sun-o hidden dark:inline text-yellow-400"></i>
          </button>
          <button 
            class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
            aria-label="设置"
          >
            <i class="fa fa-cog text-gray-600 dark:text-gray-300"></i>
          </button>
        </div>
      </div>
    </header>

    <!-- 聊天内容区域 -->
    <main class="flex-1 overflow-y-auto p-4 scrollbar-hide" ref="chatContainer">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="flex flex-col items-center justify-center h-full text-center p-6">
        <div class="w-24 h-24 rounded-full bg-gradient-to-br from-indigo-100 to-purple-100 dark:from-indigo-900/30 dark:to-purple-900/30 flex items-center justify-center mb-6 animate-pulse-slow">
          <i class="fa fa-robot text-4xl text-indigo-500 dark:text-indigo-400"></i>
        </div>
        <h2 class="text-2xl font-bold mb-2">欢迎使用豆包AI助手</h2>
        <p class="text-gray-500 dark:text-gray-400 max-w-md">我是豆包，一个智能助手。有什么我可以帮助你的吗？</p>
      </div>

      <!-- 聊天消息列表 -->
      <div class="space-y-6">
        <template v-for="(message, index) in messages" :key="index">
          <!-- 用户消息 -->
          <div v-if="message.sender === 'user'" class="flex items-end justify-end animate-fade-in">
            <div class="max-w-[80%] bg-indigo-500 text-white p-4 rounded-2xl rounded-tr-none shadow-message">
              <p class="whitespace-pre-wrap">{{ message.content }}</p>
              <span class="text-xs opacity-75 block mt-1 text-right">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div class="ml-3 w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
              <i class="fa fa-user text-gray-600 dark:text-gray-300"></i>
            </div>
          </div>

          <!-- AI消息 -->
          <div v-else class="flex items-end animate-fade-in">
            <div class="mr-3 w-8 h-8 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
              <i class="fa fa-robot text-white"></i>
            </div>
            <div class="max-w-[80%] bg-white dark:bg-gray-800 p-4 rounded-2xl rounded-tl-none shadow-message">
              <p class="whitespace-pre-wrap">{{ message.content }}</p>
              <span class="text-xs text-gray-400 block mt-1 text-right">{{ formatTime(message.timestamp) }}</span>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="message.loading" class="flex items-end animate-fade-in">
            <div class="mr-3 w-8 h-8 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
              <i class="fa fa-robot text-white"></i>
            </div>
            <div class="bg-white dark:bg-gray-800 p-4 rounded-2xl rounded-tl-none shadow-message">
              <div class="flex space-x-2">
                <div class="w-2 h-2 rounded-full bg-indigo-500 animate-bounce"></div>
                <div class="w-2 h-2 rounded-full bg-indigo-500 animate-bounce" style="animation-delay: 0.2s"></div>
                <div class="w-2 h-2 rounded-full bg-indigo-500 animate-bounce" style="animation-delay: 0.4s"></div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </main>

    <!-- 输入区域 -->
    <footer class="bg-white dark:bg-gray-800 p-4 shadow-lg z-10">
      <div class="container mx-auto">
        <form @submit.prevent="sendMessage" class="flex flex-col space-y-3">
          <div class="relative">
            <textarea
              v-model="userInput"
              @keydown.enter.exact.prevent="sendMessage"
              @keydown.enter.shift="userInput += '\n'"
              class="w-full px-4 py-3 pr-12 rounded-xl border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent outline-none transition-all resize-none"
              placeholder="输入你的问题... 按Shift+Enter换行，按Enter发送"
              rows="3"
              :disabled="isLoading"
            ></textarea>
            <button 
              type="submit"
              :disabled="!userInput.trim() || isLoading"
              class="absolute right-3 bottom-3 p-2 rounded-full bg-indigo-500 text-white hover:bg-indigo-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
              aria-label="发送消息"
            >
              <i class="fa fa-paper-plane"></i>
            </button>
          </div>
          <p class="text-xs text-gray-500 dark:text-gray-400 text-center">
            豆包AI会尽力提供准确的信息，但有时可能会出错。请谨慎使用重要信息。
          </p>
        </form>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';

// 状态管理
const userInput = ref('');
const messages = ref([]);
const isLoading = ref(false);
const chatContainer = ref(null);

// 初始化 - 检查深色模式偏好
onMounted(() => {
  if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
  
  // 监听消息变化，自动滚动到底部
  watch(messages, () => {
    scrollToBottom();
  }, { deep: true });
});

// 切换深色模式
const toggleDarkMode = () => {
  if (document.documentElement.classList.contains('dark')) {
    document.documentElement.classList.remove('dark');
    localStorage.theme = 'light';
  } else {
    document.documentElement.classList.add('dark');
    localStorage.theme = 'dark';
  }
};

// 发送消息
const sendMessage = async () => {
  const content = userInput.value.trim();
  if (!content || isLoading.value) return;

  // 添加用户消息
  messages.value.push({
    sender: 'user',
    content,
    timestamp: new Date()
  });

  // 清空输入框
  userInput.value = '';

  // 显示加载状态
  isLoading.value = true;
  messages.value.push({
    sender: 'ai',
    loading: true
  });

  try {
    // 调用豆包AI API (这里使用模拟数据)
    const response = await callDoubaoAI(content);
    
    // 移除加载状态
    messages.value.pop();
    
    // 添加AI回复
    messages.value.push({
      sender: 'ai',
      content: response,
      timestamp: new Date()
    });
  } catch (error) {
    // 处理错误
    messages.value.pop();
    messages.value.push({
      sender: 'ai',
      content: '抱歉，我暂时无法提供回复。请稍后再试。',
      timestamp: new Date()
    });
    console.error('API调用错误:', error);
  } finally {
    isLoading.value = false;
  }
};

// 模拟调用豆包AI API
const callDoubaoAI = async (prompt) => {
  // 实际使用时替换为真实API调用
  return new Promise((resolve) => {
    // 模拟网络延迟
    setTimeout(() => {
      // 根据不同问题返回不同回答
      const responses = {
        '你好': '你好！我是豆包AI助手，很高兴为你服务。有什么我可以帮助你的吗？',
        '你能做什么': '我可以回答各种问题、提供信息、帮助解决问题、进行对话交流等。你可以问我任何事情，我会尽力为你提供帮助。',
        '今天天气怎么样': '抱歉，我目前无法获取实时天气信息。你可以尝试查询当地的天气应用或网站获取最新的天气情况。',
        '再见': '再见！如果你还有其他问题，随时可以来找我。祝你有愉快的一天！'
      };
      
      // 如果没有匹配的预设回答，返回默认回答
      resolve(responses[prompt] || `感谢你的提问："${prompt}"。这是一个模拟的回复。在实际应用中，这里会显示豆包AI的真实回答。`);
    }, 1500);
  });
};

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// 滚动到最新消息
const scrollToBottom = () => {
  if (chatContainer.value) {
    setTimeout(() => {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }, 100);
  }
};
</script>

<style scoped>
/* 自定义动画和工具类 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes pulseSlow {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}

.animate-pulse-slow {
  animation: pulseSlow 2s infinite;
}

.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.scrollbar-hide::-webkit-scrollbar {
  display: none;
}

/* 基础样式扩展 */
textarea {
  scrollbar-width: thin;
  scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
}

textarea::-webkit-scrollbar {
  width: 4px;
}

textarea::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
  border-radius: 2px;
}
</style>
    